$(function () {
    layui.use(['element', 'laydate', 'table', 'layer', 'form','laytpl'], function () {
        var laydate = layui.laydate,
            table = layui.table,
            layer = layui.layer,
            element = layui.element,
            form = layui.form,
            laytpl = layui.laytpl;
        var checkData = [], areaList = [], gatewayList = [], sensorList = [];
        var devTypeObj = {
            1: {name: '水', unit:'T'},
            0: {name: '电', unit:'kW·h'}
        };
        init();

        function init() {
            getAllMeters();
            getAllAreas();
            getGatewayData();
            getSensorData();
        }

        //查
        function getAllMeters() {
            $.ajax({
                type: "GET",
                url: ctx + "/meterManager/queryAllMeter.do",
                data: {},
                dataType: "json",
                success: function (data) {
                    var flag = hasAuth("system_auth");
                    renderTable(data)
                }
            });
        }

        function hasAuth(authCode) {
            var authArray = authStr.split(",");
            if (authArray && authArray.length > 0) {
                for (var i = 0; i < authArray.length; i++) {
                    if (authArray[i].trim() == authCode) {
                        return true;
                    }
                }
            }
            return false;
        }

        if (hasAuth("system_auth")) {
            $('div[lay-filter="tabchange"] ul').removeClass('hidden');
            $('.layui-tab-item.exceptionTab').removeClass('hidden');
            $('.layui-tab-title').removeClass('hidden');
        } else {
            $('.system_auth').remove();
            $('.system_auth_2').hide();

        }

        //渲染表格
        function renderTable(data) {
            var tbHeigth = $('.settings-wrap').height();
            table.render({
                elem: '#deviceTable',
                data: data,
                height: tbHeigth,
                title: '设备信息表',
                toolbar: '#toolbar',
                defaultToolbar: [],
                cols: [[
                    {type: 'radio', fixed: 'left'}
                    , {field: 'areaName', title: '区域'}
                    // , {field: 'deviceTypeCode', title: '设备类型',templet: function (d) {
                    //       return  devTypeObj[d.deviceTypeCode].name + '表'
                    //     }}
                    , {field: 'anotherName', title: '监控位置'}
                    , {field: 'deviceName', title: '监控位置编号'}
                    , {field: 'standard', title: '日标准量'}
                    , {field: 'gatewayName', title: 'IP简称'}
                    , {field: 'readerCode', title: '仪表识别码'}
                    , {field: 'descrition', title: '备注'}
                ]],
                page: {
                    layout: ['prev', 'page', 'next', 'count', 'skip', 'limit']
                    , groups: 5 //只显示 5 个连续页码
                    , limit: 15  //每页显示条数
                    , limits: [15, 30, 45, 60]
                },
                loading: true,
                done: function () {
                    $('.layui-table-view > .layui-table-box').height(tbHeigth - 41);
                    $('.layui-table-view > .layui-table-box .layui-table-body').height(tbHeigth - 80);
                }
            });
        }

        //头工具栏单选事件
        table.on('toolbar(deviceTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id); //获取选中行状态
            switch (obj.event) {
                case 'getCheckData':
                    checkData = checkStatus.data;  //获取选中行数据
                    // console.log(checkData);
                    break;
            }
        });

        // 新增
        $('.addBtn').click(function () {
            var layerIdx = layer.open({
                type: 1,
                title: "新增",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#add-tpl').html(),
                success: function (layero) {
                    renderForm(layero);
                }
            });
            form.on('submit(add-param)', function (res) {
                // console.log(res.field); //当前容器的全部表单字段，名值对形式：{name: value}
                addDevice(res.field,layerIdx);
                // layer.close(layerIdx);
                return false;
            });
            $(".add-param button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        });

        // 编辑
        $('.editBtn').click(function () {
            $('.getCheckData').click();
            if (checkData.length === 1) {
                var layerIdx = layer.open({
                    type: 1,
                    title: "编辑",
                    closeBtn: 1,
                    anim: 0,
                    area: 'auto',
                    content: $('#edit-tpl').html(),
                    success: function (layero) {
                        renderForm(layero);
                    }
                });
                form.val("edit-param", checkData[0]);
                form.on('submit(edit-param)', function (res) {
                    // console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
                    updateDevice(res.field,layerIdx);
                    layer.close(layerIdx);
                    return false;
                });
                $(".edit-param button[type='cancel']").click(function () {
                    layer.close(layerIdx);
                    return false;
                });
            } else {
                layer.alert('请选择一条数据')
            }
        });

        // 删除
        $('.deleteBtn').click(function () {
            $('.getCheckData').click();
            if (checkData.length === 1) {
                var layerIdx = layer.confirm('确认删除?', function (index) {
                    // console.log(checkData[0]);
                    deleteDevice(checkData[0]);
                    layer.close(index);
                });
            } else {
                layer.alert('请选择一条数据')
            }
        });

        // 设置频率
        $('.intervalBtn').click(function () {
            var layerIdx = layer.open({
                type: 1,
                title: "设置频率",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#interval-tpl').html()
            });
            form.on('submit(interval-param)', function (res) {
                // console.log(res.field); //当前容器的全部表单字段，名值对形式：{name: value}
                updateInterval(res.field);
                layer.close(layerIdx);
                return false;
            });
            $(".interval-param button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        });

        // 增
        function addDevice(data,layerIdx) {
            $.ajax({
                type: "POST",
                url: ctx + "/meterManager/add.do",
                data: data,
                dataType: "json",
                success: function (result) {
                    if (result.code == '000000') {
                        getAllMeters();
                        layer.close(layerIdx);
                    } else {
                        layer.alert(result.message)
                    }
                }
            });
        }

        //删
        function deleteDevice(data) {
            $.ajax({
                type: "POST",
                url: ctx + "/meterManager/delete.do",
                data: {"meterCode":data.meterCode},
                dataType: "json",
                success: function (result) {
                    if (result.code == '000000') {
                        getAllMeters();
                    } else {
                        layer.alert(result.message)
                    }
                }
            });
        }

        // 改
        function updateDevice(obj,layerIdx) {
            $.ajax({
                url: ctx + "/meterManager/update.do",
                type: "post",
                data: obj,
                success: function (result) {
                    if (result.code == '000000') {
                        getAllMeters();
                        layer.close(layerIdx);
                    } else {
                        layer.alert(result.message)
                    }
                }
            });
        }

        // 改频率
        function updateInterval(obj) {
            $.ajax({
                url: ctx + "/meterManager/setIntervalTime.do",
                type: "post",
                data: obj,
                success: function (result) {
                    if (result.code == '000000') {
                        getAllMeters();
                    } else {
                        layer.alert(result.message)
                    }
                }
            });
        }

        // 获取区域
        function getAllAreas(){
            $.ajax({
                type: "GET",
                url: ctx + "/areaManger/areaAll.do",
                dataType: "json",
                success: function (data) {
                    if (data != null) {
                        areaList = data;
                    }
                }
            });
        }

        // 获取网关
        function getGatewayData() {
            $.ajax({
                type: "post",
                url: ctx + "/gatewayManage/getAll.do",
                data: {},
                dataType: "json",
                success: function (data) {
                    if (data != null) {
                        gatewayList = data
                    }
                }
            });
        }

        // 获取传感器
        function getSensorData() {
            $.ajax({
                type: "post",
                url: ctx + "/sensorManage/getAll.do",
                data: {},
                dataType: "json",
                success: function (data) {
                    if (data != null) {
                        sensorList = data
                    }
                }
            });
        }

        function renderForm(layero){
            var areaTpl = $('#area-tpl').html();
            laytpl(areaTpl).render(areaList, function(html){
                layero.find('.areaMenu').html(html);
            });
            var gatewayTpl = $('#gateway-tpl').html();
            laytpl(gatewayTpl).render(gatewayList, function(html){
                layero.find('.gatewayMenu').html(html);
            });
            var sensorTpl = $('#sensor-tpl').html();
            laytpl(sensorTpl).render(sensorList, function(html){
                layero.find('.sensorMenu').html(html);
            });
            form.render();
        }

    });

});
